#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 将需刷新的url填写到 /data/urls.ini 文件中

import urllib2
import json
import sys
import os


token = "94675ee22e5f3bbfc0c9d5693c4eb5b6"
host_url = "https://api.qingcdn.com/v2/cache/refresh?token=%s" % token
url_file = "/data/urls.ini"
urls = []
urls_dir = []
status_code_list = {
    "404": "您输入的 URL 错误",
    "401": "鉴权错误，您的 token 可能是不对的",
    "400": "请求参数有误",
    "200": "刷新成功",
}


def httpRequset(host_url, data, header, req_timeout=30):
    try:
        req = urllib2.Request(host_url, data, headers=header)
        req_timeout = 30
        response = urllib2.urlopen(req, None, req_timeout)
        status_code = str(response.getcode())
        response_info = json.loads(response.readlines()[0])
        print("状态码:%s\n结果信息:%s" % (status_code, status_code_list[status_code]))
        if response_info['data']['count'] != len(json.loads(data)['urls']):
            print('以下url刷新失败:%s' % '\n'.join(
                response_info['data']['err_urls']))
    except urllib2.HTTPError:
        print("http 访问出错")


try:
    with open(url_file, 'rw') as f:
        for line in f:
            tmp = line.strip('\n')
            if os.path.isdir(tmp):
                urls_dir.append(tmp)
            elif os.path.isfile(tmp):
                urls.append(tmp)
        '''
        if len(urls) == 0 and len(urls_dir) == 0:
            print("%s 为空" % url_file)
            sys.exit(1)
        '''
except IOError:
    print("读取文件 %s 错误" % url_file)
    sys.exit(1)

data = json.dumps({"urls": urls, "type": "url"})
data_dir = json.dumps({"urls": urls_dir, "type": "dir"})
header = {"Content-Type": "application/json"}

if len(urls) != 0:
    httpRequset(host_url, data, header)
elif 
'''
try:
    req = urllib2.Request(host_url, data, headers=header)
    req_timeout = 30
    response = urllib2.urlopen(req, None, req_timeout)
    status_code = str(response.getcode())
    response_info = json.loads(response.readlines()[0])
    print("状态码:%s\n结果信息:%s" % (status_code, status_code_list[status_code]))
    if response_info['data']['count'] != len(urls):
        print('以下url刷新失败:%s' % '\n'.join(response_info['data']['err_urls']))
except urllib2.HTTPError:
    print("http 访问出错")
'''
